"use strict";

var net = require('net');



class TCPClient {
  constructor() {
    this.ip = "localhost"
    this.port = 80
    this.isok = false
    this.client = false
    this._ondata = function(data){}

  }
  open(ip, port){
    this.ip = ip || this.ip
    this.port = parseInt(port) || this.port
    this.client = false
    this.isok = false
    var that = this

    try {
      this.client = new net.Socket();
      this.client.setNoDelay(true)
      this.client.on('data', function(data) {
          that._ondata(data)
          // console.log("data",data)
      });
      this.client.on('error', function(err) {
        that.isok=false;
        that.error(err.message)

      });
      this.client.on('close', function() {
        that.isok=false;
      });

      this.client.connect(this.port, this.ip, function() {
        that.isok=true;

      });

    } catch (e) {
      that.isok=false;
      that.error(e)
      // console.log("error:",e);

    }



  }
  stop(){
    try {
      if (this.isok) this.client.end()
    } catch (e) {
      // this.error(e)
    }

  }
  send(msg){
    try {
      if (this.isok){
        if (typeof(msg)=='string'){
          msg = Buffer.from(msg)
        }
        this.client.write(msg)
      }
    } catch (e) {
      this.error(e)
    }

  }
  ondata(cb){
    try {
      // console.log("call cb");
      this._ondata=cb;
    } catch (e) {
      this.error(e)
    }
  }
  update_status(cb){
    var that = this
    setInterval(()=>{
      cb(that.isok,that)
    },100);
  }
  log(msg){
    console.log(msg);
  }
  error(msg){
    console.error(msg);
  }
  onlog(cb){
    this.log=cb;
  }
  onerror(cb){
    this.error=cb;
  }

}

var client = new TCPClient()

module.exports = client
